var roomtypeId = 0;
var roomId = 0;
var span = 1;
var date = null;
var spanFormDate;
var price = 0;
var res = 0;
var groupId = 0;
var roomNum = 1;
function UniqueString(data)
{
	var tmp = {}, out = [];
	for(var i = 0, n = data.length; i < n; ++i)
	{
		if(!tmp[data[i]]) { 
			tmp[data[i]] = true; 
			out.push(data[i]); 
		}
	}
	return out;
}
function UniqueStringResIds(data)
{
	var tmp = {}, out = [];
	for(var i = 0, n = data.length; i < n; ++i)
	{
		if(!tmp[data[i].id]) { 
			tmp[data[i].id] = true; 
			out.push(data[i]); 
		}
	}
	return out;
}
function UniqueArray(data)
{
	var tmp = {}, out = [];
	for(var i = 0, n = data.length; i < n; ++i)
	{
		if(!tmp[data[i].groupId]) { 
			if(data[i].groupId==0){
				tmp[data[i].groupId] = false;
			}else{
				tmp[data[i].groupId] = true;
			}
			out.push(data[i]); 
		}
	}
	return out;
}
function checkPopup(e) {
	waitingDialog();
	$("#edit_pay").html($('#pledge').val());
	if(e.id != "detailbooking"){
		if ($("#name3").val() == "") {
			closeWaitingDialog();
			simpleDialog(WarningMessage_FillName,null,function(){$("#name3").focus();});
			return false;
		}
		if ($("#tel3").val() == "") {
			closeWaitingDialog();
			simpleDialog(WarningMessage_FillTel,null,function(){$("#tel3").focus();});
			return false;
		}
		bookingGG(e);
	}else{
		var amount = $("#roomAmount3").val();
		var type = (amount==1)? "btnEditS" : "btnEditG";
		if($("div[forload=editreserved] [name=editReserved_group]").size() == 0){
			waitingDialog();
			document.callEditReservedPagetype = type;
			var div = $("<div>");
			$("div[forload=editreserved]").append(div);
			div.load("/components/EditReserved/EditReserved.jsp",function(){
				var type = document.callEditReservedPagetype;
				delete document.callEditReservedPagetype;
				CallEditReseredPage(type,0);
			});
		}
		else{CallEditReseredPage(type,0)}
	}
}

function defualtPopup() {
	var SeasonalRate = document.getElementById('name3');
	roomNum = 1;
	SeasonalRate.focus();
	row5.style.display = 'none';
	row6.style.display = 'none';
	document.getElementById('name3').focus();
	document.getElementById('salutation3').selectedIndex = 0;
	document.getElementById('roomAmount3').selectedIndex = 0;
	document.getElementById('SeasonalRate3').selectedIndex = 0;
	document.getElementById('SeasonalRate').selectedIndex = 0;
	document.getElementById('child3').selectedIndex = 0;
	document.getElementById('adult3').selectedIndex = 0;
	document.getElementById('name3').value = "";
	document.getElementById('lastname3').value = "";
	document.getElementById('tel3').value = "";
	document.getElementById('email3').value = "";
	document.getElementById('pledge').value = 0.00;
	document.getElementById('dep').textContent = 0.00;
	document.getElementById('dep3').textContent = 0.00;
	document.getElementById('nameAgent3').value = "";
}


function BookingDetailsS() {
	$('#BookingDetailsS').css('overflow', 'hidden');
	$("#BookingDetailsS").dialog({
		height : 310,
		width : 600,
		modal : true,
		resizable : false,
		show : {
			effect : "blind",
			duration : 500,
			draggable : false,
		}
	});

var header = "<div style='display:inline-block'>"+Popup_Preemption+"</div><div style='display:inline-block;float:right'>"+Popup_ResId+" #"+res+"</div>";
$("#BookingDetailsS").parents(".ui-dialog:first").find(".ui-dialog-title").html(header);
}
function BookingDetailsG() {
	$('#BookingDetailsG').css('overflow', 'hidden');
	$("#BookingDetailsG").dialog({
		height : 310,
		width : 600,
		modal : true,
		resizable : false,
		draggable : false,
		show : {
			effect : "blind",
			duration : 500,
		}
	});
	var header = "<div style='display:inline-block'>ใบจองห้องพัก(กลุ่ม)</div><div style='display:inline-block;float:right'> #G"+getObjFromCell(this).gId+"</div>";
	$("#BookingDetailsG").parents(".ui-dialog:first").find(".ui-dialog-title").html(header);
}

function setTabindex(){
	if(row5.style.display == false){
		document.getElementById('roomAmount3').tabIndex = 1;
		document.getElementById('SeasonalRate').tabIndex = 2;
		document.getElementById('adult3').tabIndex = 3;
		document.getElementById('child3').tabIndex = 4;
		document.getElementById('salutation3').tabIndex = 5;
		document.getElementById('name3').tabIndex = 6;
		document.getElementById('lastname3').tabIndex = 7;
		document.getElementById('tel3').tabIndex = 8;
		document.getElementById('email3').tabIndex = 9;
		document.getElementById('pledge').tabIndex = 10;
		document.getElementById('booking').tabIndex = 11;
		document.getElementById('checkin').tabIndex = 12;
		document.getElementById('tempbooking').tabIndex = 13;	
	}else{
		document.getElementById('roomAmount3').tabIndex = 1;
		document.getElementById('adult3').tabIndex = 2;
		document.getElementById('child3').tabIndex = 3;
		document.getElementById('salutation3').tabIndex = 4;
		document.getElementById('name3').tabIndex = 5;
		document.getElementById('lastname3').tabIndex = 6;
		document.getElementById('tel3').tabIndex = 7;
		document.getElementById('email3').tabIndex = 8;
		document.getElementById('pledge').tabIndex = 9;
		document.getElementById('nameAgent3').tabIndex = 10;
		document.getElementById('SeasonalRate3').tabIndex = 11;
		document.getElementById('booking').tabIndex = 12;
		document.getElementById('checkin').tabIndex = 13;
		document.getElementById('tempbooking').tabIndex = 14;	
	}
}
function BookingDrag(roomName, roomType, dateFrom, dateTo, spann) {
	if(roomName==null||dateFrom == undefined || dateFrom == null) return;
	waitingDialog({});
	var services = [];
	services.push(["/popupService",{doClass:"loadSalutation"},"Salutation",null]);
	services.push(["/taxService",{func:"getRoomTax"},"RoomTax",null]);
	services.push(["/popupService",{doClass : "loadPackage"},"Package",null]);
	loadSharedDataIfNotExist(services,function(obj){
		defualtPopup();
		var date = obj.dateFrom.toFormatString('yyyy-MM-dd');
		roomId = obj.roomName;
		dateStart.textContent = $.datepicker.parseDate("yy-mm-dd",date).getFormatedDateAndMonthString();
		dateStart.setAttribute("dateform",date);
		dateEnd.textContent = $.datepicker.parseDate("yy-mm-dd",date).addDate(obj.spann).getFormatedDateAndMonthString();
		dateEnd.setAttribute("dateend",$.datepicker.parseDate("yy-mm-dd",date).addDate(obj.spann).toFormatString("yyyy-MM-dd"));
		roomtypeId = obj.roomType;
		span = obj.spann;
		this.spanFormDate = obj.spann;
		fillSalutation();
		fillPackage(obj.roomType, obj.dateFrom, obj.spann);
		fillOccupancy(obj.roomType);
		loadRoom(obj.roomType, date);
		setTabindex();
		
		$("#BookingG").dialog({
			height : 196,
			width : 733,
			resizable : false,
			modal : true,
			open: function(){
				SeasonalRate.disabled = false;
				dep.style.display = '';
				$("#commoncus").html(Popup_btnAgent);
				$(this).css("height",166);
			}
		});
		//$("#BookingG").parents(".ui-dialog").draggable({handle:'#edit_new_dialog_header'});
			EditDialogHeader(obj.roomName, obj.roomType);
			loadRoomOnPopup(obj.roomType,obj.dateFrom.toFormatString('yyyy-MM-dd'),span,loadRoomOnPopupBookingCallBack);
		$("[name=\"isAssign\"]").show();
		closeWaitingDialog();
	},{roomName:roomName, roomType:roomType, dateFrom:dateFrom, spann:spann});
}

function BookingG(e) {
	waitingDialog();
	var services = [];
	services.push(["/popupService",{doClass:"loadSalutation"},"Salutation",null]);
	services.push(["/taxService",{func:"getRoomTax"},"RoomTax",null]);
	services.push(["/popupService",{doClass : "loadPackage"},"Package",null]);
	loadSharedDataIfNotExist(services,function(){
		defualtPopup();
		var checkToDrow = e.getAttribute("order");
		var date = $(e).parents("[date]").attr("date");
		var roomtype = $(e).parents("[roomtype]:first").attr("roomtype");
		roomId = $(e).parents("[roomname]:first").attr("roomname");
		dateStart.textContent = $.datepicker.parseDate("yy-mm-dd",date).getFormatedDateAndMonthString();
		dateStart.setAttribute("dateform",date);
		dateEnd.textContent = $.datepicker.parseDate("yy-mm-dd",date).addDate(1).getFormatedDateAndMonthString();
		dateEnd.setAttribute("dateend",$.datepicker.parseDate("yy-mm-dd",date).addDate(1).toSystemFormat());
		roomtypeId = roomtype;
		if (e.innerHTML == "") {
			fillSalutation();
			fillPackage(roomtype,$.datepicker.parseDate("yy-mm-dd",date),1);
			fillOccupancy(roomtype);
			loadRoom(roomtype, date);
			document.getElementsByTagName('select').selectedIndex = 0;
			setTabindex();
			closeWaitingDialog();
			$("#BookingG").dialog({
				height : 196,
				width : 733,
				resizable : false,
				modal : true,
				show : {
					effect : "blind",
					duration : 500
				},
				open: function(){
					SeasonalRate.disabled = false;
					dep.style.display = '';
					$("#commoncus").html(Popup_btnAgent);
					$(this).css("height",166);
				}
			});
			$('#tempbooking').css('cursor','pointer');
			$('#tempbooking').css('color','#555454');
			$('#tempbooking').removeAttr('disabled');
			 
			$('#checkin').css('cursor','pointer');
			$('#checkin').css('color','#555454');
			$('#checkin').removeAttr('disabled');
			
			EditDialogHeader(roomId, roomtype);
			loadRoomOnPopup(roomtype,date,1,loadRoomOnPopupBookingCallBack);
			if($(event.target).parents('[date]').attr('date')!=getDate().toSystemFormat()){
				$('#checkin').attr('disabled', 'disabled');
				$('#checkin').css('cursor','auto');
				$('#checkin').css('color','#727272');
			}
			$("[name=\"isAssign\"]").show();
		}
	});
}
function loadRoomOnPopupBookingCallBack(data)
{
	var objArray = JSON.parse(data);
	
	var opts = objArray.length;
	for ( var i = 0; i < opts; i++)
		$("[name=roomOnPopup]").append( $("<option>").val(objArray[i].id).html(objArray[i].roomName));	
	$("select[name=roomOnPopup]").val(roomId); 
}
function showBooking(e) {
	waitingDialog();
	var obj = getObjFromCell(e);
	var isAssign = obj.A;
	var resId = $(e).attr("res");
	res = resId;
	var link = "/popupService?doClass=loadPopShowData&resId=" + resId;
	$.ajax({
		// Call
		url : link,
		type : "get",
		data : {
			format : "json"
		},
		datatype : "json",
		timeout : 2000,

		// if Call Success //
		success : function(data) {
			var objArray = JSON.parse(data);
			$('.adult').text(objArray['adult']);
			$('.child').text(objArray['child']);
			var aDate = new Date(objArray['date']);
			$(".dateCheckin").text(aDate.getFormatedString());
			$(".dateCheckout").text(aDate.addDate(objArray['span']).getFormatedString());			
			$('.roomId').text(objArray['roomName']);
			$('.daySpan').text(objArray['span']);
			$('.ownerId').text(objArray['ownerGroupId']);
			$('.ownerName').text(objArray['ownerGroupName']);
			$('.payG').html(toCurrencyString(parseFloat(objArray['payGroup'])));
			$('.pay').html(toCurrencyString(parseFloat(objArray['pay'])));
			$('.total').html(toCurrencyString(parseFloat(objArray['total'])));
			$('.totalG').html(toCurrencyString(parseFloat(objArray['totalGroup'])));
			$('.remain').html(toCurrencyString(parseFloat(objArray['balance'])));
			$('.remainG').html(toCurrencyString(parseFloat(objArray['balanceGroup'])));
			if(objArray['guestId'] != null){
				$("#tagGuest").css("display","");
				$("#tagGuest2").css("display","");
				$(".guestId").css("display","");
				$('.guestId').text(objArray['guestId']);
				$('.guestname').text(objArray['guestName']);
				$('.address').text(objArray['address']);
				$('.tel').text(objArray['tel']);
				$('.email').text(objArray['email']);
			}else{
				$("#tagGuest").css("display","none");
				$("#tagGuest2").css("display","none");
				$(".guestId").css("display","none");
				$('.guestId').text("-");
				$('.guestname').text("-");
				$('.address').text("-");
				$('.tel').text("-");
				$('.email').text("-");
			}
			$('.seasonalRate').text(objArray['packageName']);
			$('.roomtypename').text(objArray['roomtypeName']);
			$('.agency').text(objArray['agency']);
			groupId = objArray['groupId'];
			$('#BookingDetailsG').get(0).resId = groupId;
		//-----------------popup header add groupId and first resIdin group------------------//	
		var header= Popup_Preemption+"("+Popup_Group+")&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+Popup_ResId+"                         #"+res+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;"+Popup_GroupId+" #G"+groupId;
		$("#BookingDetailsG").find("table:first").replaceWith("<table><tr><td>"+header+"</td></tr></table>");
		//$("#BookingDetailsG").parent().children().children()[0].innerHTML=header;
		//----------------------------------------------------------------------------------//
		},

	});
	$("[name=\"isAssign\"]").hide();
	if(obj.gId != 0){
		BookingDetailsG();
	}else{
		BookingDetailsS();
	}
	$('#BookingDetailsS').get(0).resId = resId;
	
	closeWaitingDialog();
}
function fillSalutation() {
	$("#salutation3").find("option").not(":first").remove();
	if(SharedData.Salutation == null) return;
	for(i=0;i<SharedData.Salutation.length;i++)
		$("#salutation3").append("<option value='" + SharedData.Salutation[i].id + "'>" + SharedData.Salutation[i].title + "</option>");
}
function fillPackage(roomType,dateFrom,span) {
	$("select[id*=SeasonalRate]").find("option").remove();
	var Obj = JSON.parse(JSON.stringify(SharedData.Package));
	
	//filter for screen package rate
	for(var i=0;i<Obj.length;i++)
		if(getObjectFromDataIndex(Obj[i].packagepriceList,"roomtypeString",roomType) != null)
			$("select[id*=SeasonalRate]").append(optionString.format(Obj[i].id,Obj[i].Name));

	resonalrateChange();
}
function fillOccupancy(roomType){
	var max = getRoomTypeId(roomType).MaxOccupancy;
	
	$('#adult3').find("option").remove();
	for(var i=1;i<=max;i++)
		$('#adult3').append(optionString.format(i,i));

	$('#child3').find("option").remove();
	for(var i=0;i<max;i++)
		$('#child3').append(optionString.format(i,i));
}
function calOcc(roomType){
	var child = parseInt($('#child3').val());
	var adult = parseInt($('#adult3').val());
	var max = getRoomTypeId(roomType).MaxOccupancy;
	
	$('#adult3').find("option").remove();
	for(var i=1;i<=(max-child);i++)
		$('#adult3').append(optionString.format(i,i));
	$('#adult3').val(adult);
	
	$('#child3').find("option").remove();
	for(var i=0;i<=(max-adult);i++)
		$('#child3').append(optionString.format(i,i));
	$('#child3').val(child);
}
function loadRoom(roomtype, date) {
	var link = "/popupService?doClass=loadRoom&roomtype=" + roomtype + "&date=" + date+"&span="+span;
	simpleservice(link,null,successLoadRoom);
}
function successLoadRoom(data) {
	var objArray = JSON.parse(data);
	var ddlRoom = document.getElementById('roomAmount3');
	ddlRoom.options.length = objArray;
	ddlRoomLength = ddlRoom.options.length;
	for ( var i = 0; i < ddlRoomLength; i++) {
		ddlRoom.options[i].text = "" + (i + 1);
		ddlRoom.options[i].value = "" + (i + 1);
	}
}
function chkNum(ele) {
	if(ele.value==""){ele.value=0;}
	 if(ele.value != 0){
		 $('#tempbooking').css('cursor','auto');
		 $('#tempbooking').css('color','#727272');
		 $('#tempbooking').attr('disabled',true);
	 }else{
		 $('#tempbooking').css('cursor','pointer');
		 $('#tempbooking').css('color','#555454');
		 $('#tempbooking').removeAttr('disabled');
	 }
	var num = parseFloat(ele.value);
	ele.value = num.toFixed(SharedData.General.currencyDecimalPlaces);
}

function bookingGG(e) { 
	if (e.getAttribute('id') == "booking") {
		var reservationstatus = "Reserved Rooms";
	} else if (e.getAttribute('id') == "checkin") {
		var reservationstatus = "Reserved Rooms";
	} else if (e.getAttribute('id') == "tempbooking") {
		var reservationstatus = "Temp Rooms";
	}
	var hotelId = $('#hotelId').val();
	var adult = $('#adult3:visible').val();
	var child = $('#child3:visible').val();
	var salutation = $('#salutation3:visible').val();
	var name = $('#name3:visible').val();
	var lastname = $('#lastname3:visible').val();
	var tel = $('#tel3:visible').val();
	var email = $('#email3:visible').val();

	if ($('#pledge:visible').val() == null
			|| $('#pledge:visible').val() == "") {
		var pay = 0;
	} else {
		var pay = $('#pledge:visible').val();
	}

	roomNum = $('#roomAmount3:visible').val();

	if ($('#SeasonalRate:visible').val() != "1") {
		var priceRate = $('#SeasonalRate:visible').val();
	} else {
		var priceRate = $('#SeasonalRate').val();
	}
	var roomIdd = roomId;
	var roomTypeIdd = roomtypeId;
	var timeStamp = new Date();
	var isA = $("[name=\"isAssign\"]").is(":checked");
	var guestId = 0;
	var agencyId = 0;
	var date = $(e).parents("#BookingG").find("#dateStart").attr("dateform");

	var agency = $('#nameAgent3').val();
	var link = "/reservationService?func=CreateRes"
			+ "&date=" + date + "&span=" + span + "&rmId=" + roomId
			+ "&rmType=" + roomtypeId + "&priceRate=" + priceRate + "&adult="
			+ adult + "&child=" + child + "&isA=" + isA
			+ "&guest=" + guestId + "&ReservationStatus=" + reservationstatus
			+ "&sal=" + salutation + "&nm=" + name + "&lsNm=" + lastname
			+ "&phone=" + tel + "&mail=" + email + "&roomamount="+roomNum+"&agency="
			+ agency+"&agencyId="+agencyId+"&pay="+pay;
	var o = {
		roomName: getObjectFromSharedData(SharedData.Room,roomId).roomName,
		date: date
	};
	simpleserviceWithArgs(link,null,function(data,o) {
		var objArray = JSON.parse(data);
		var checkLogOut =  CheckSession(objArray);
		if(checkLogOut)
			return;
		setTimeout(function(){showNumberall_reservation();},50);
		ClearSpanSelection();
		if ((objArray.result==true||objArray.result)) {
			cerltimespan(savedSpan);
			span = 1;
			$("#BookingG").dialog("close");
			if(objArray.groupId!=0){
				if($("div[forload=editreserved] [name=editReserved_group]").size() == 0){
					var divs = $("<div>");
					document.OpendetailPage = objArray.groupId;
					$("div[forload=editreserved]").append(divs);
					waitingDialog();
					if (e.getAttribute('id') == "checkin")
						divs.load("components/EditReserved/EditReserved.jsp",function(){
							var gId = document.OpendetailPage;
							delete document.OpendetailPage;
							CallEditReseredPage("btnEditG",gId);
						});
				}else{
					CallEditReseredPage("btnEditG",objArray.groupId);
				}
			}
			closeWaitingDialog();
		}else{
			span = 1;
			simpleDialog("Cannot Resere Room:{0} ,Date:{1}".format(o.roomName,$.datepicker.parseDate("yy-mm-dd",o.date).getFormatedString()),0,function(){cerltimespan(savedSpan)})
		}
		$("#BookingG").dialog("close");
		closeWaitingDialog();
	},o);
}
function swapBooking(e) {
	setTabindex();
	var row6 = document.getElementById("row6");
	if (row6.style.display == 'none') {
		row5.style.display = '';
		row6.style.display = '';
		var btn = $('#commoncus').get(0);
		btn.textContent = Popup_btnCustomer;
		var SeasonalRateList = $('#commoncus').get(0);
		SeasonalRate.disabled = true;
		SeasonalRate3.selectedIndex = SeasonalRate.selectedIndex;
		adult3.selectedIndex = 0;
		child3.selectedIndex = 0;
		dep.style.display = 'none';
		g1.style.display = 'none';
		$('#BookingG').css('overflow', 'hidden');
		$("#BookingG").dialog({
			height : 284,
			width : 733,
			modal : true,
			resizable: false,
			show : {
				effect : "blind",
				duration : 500
			}
		});
	} else {
		row5.style.display = 'none';
		row6.style.display = 'none';
		var btn = $('#commoncus').get(0);
		btn.textContent = Popup_btnAgent;
		var SeasonalRateList = $('#commoncus').get(0);
		SeasonalRate.disabled = false;
		SeasonalRate.selectedIndex = SeasonalRate3.selectedIndex;
		adult3.selectedIndex = 0;
		child3.selectedIndex = 0;
		dep.style.display = '';
		g1.style.display = '';
		$('#BookingG').css('overflow', 'hidden');
		$("#BookingG").dialog({
			height : 208,
			width : 733,
			modal : true,
			resizable : false,
			show : {
				effect : "blind",
				duration : 500
			}
		});
	}
}

function getPackagePrice(packageId,roomtypeId)
{
	var pkg = getObjectFromSharedData(SharedData.Package,packageId);
	if(pkg == null) return null;
	for(var i=0;i<pkg.packagepriceList.length;i++)
		if(pkg.packagepriceList[i].roomtypeString == roomtypeId) return pkg.packagepriceList[i];
	return null;
}

function resonalrateChange() {
	adult3.selectedIndex = 0;
	child3.selectedIndex = 0;
	if($('#SeasonalRate').attr('disabled') == null){
		var priceRate = $('#SeasonalRate').val();
	}else{
		var priceRate = $('#SeasonalRate3').val();
	}
	
	if($("#SeasonalRate").find("[value="+priceRate+"]").length == 0)
		priceRate = $("#SeasonalRate").find("option:first").val();
	
	var packagePrice = getPackagePrice(priceRate,roomtypeId);
	var decimalPlace = SharedData.General.currencyDecimalPlaces;
	
	if(packagePrice!= null)
	{
		var price = parseFloat(packagePrice.priceperNight);
		//var priceObj = CalRoomTaxForDisplay(price*span* roomNum,span);
		//var displayCost = priceObj.displayCost;
		var displayCost = (price*span* roomNum);
		$("#dep").html(displayCost.toFixed(decimalPlace));
		$("#dep3").html(displayCost.toFixed(decimalPlace));
	}
}

function getChildExBed(priceRate,roomtypeId,occ)
{
	var packagePrice = getPackagePrice(priceRate,roomtypeId);
	var roomtype = getRoomTypeId(roomtypeId);
	var decimalPlace = SharedData.General.currencyDecimalPlaces;
	
	var price = parseFloat(packagePrice.priceperNight);
	if(occ > getRoomTypeId(roomtypeId).StandardOccupancy)
		price = price + (packagePrice.Extrabed * (occ - getRoomTypeId(roomtypeId).StandardOccupancy));
	
	if(packagePrice!= null)
	{
		var displayCost = (price*span* roomNum);
		$("#dep").html(displayCost.toFixed(decimalPlace));
		$("#dep3").html(displayCost.toFixed(decimalPlace));
	}
}

function occChange() {
	calOcc(roomtypeId);
	roomNum = document.getElementById('roomAmount3').value;
	if (document.getElementById('SeasonalRate').value != "1") {
		var priceRate = document.getElementById('SeasonalRate').value;
	} else {
		var priceRate = document.getElementById('SeasonalRate3').value;
	}
	var occA = document.getElementById('adult3').value;
	var occC = document.getElementById('child3').value;

	getChildExBed(priceRate,roomtypeId,(parseInt(occA) + parseInt(occC)));
}
function closeDialog(id) {
	if(id =="closeG" || id == "btnEditG"){
		$("#BookingDetailsG").dialog("destroy");
	}else if(id =="closeS" || id == "btnEditS"){
		$("#BookingDetailsS").dialog("destroy");
	}else if(id == "detailbooking"){
		$("#BookingG").dialog("destroy");
	}else if(id == "closereservedG")
	{
		$("#BookingG").dialog("destroy");
		ClearSpanSelection();
	}else if(id =="closeAddToNewGroup"){
		$("#AddToNewGroup").dialog("destroy");
	}
	
}

function roomAmountChange(){
	roomNum = document.getElementById('roomAmount3').value;
}

function next(f,e){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	   {
		if(f.getAttribute('id') == 'name3'){
			document.getElementById('lastname3').focus();
			return false;
			}
		if(f.getAttribute('id') == 'lastname3'){
			document.getElementById('tel3').focus();
			return false;
			}
		if(f.getAttribute('id') == 'tel3'){
			document.getElementById('email3').focus();
			return false;
			}
		if(f.getAttribute('id') == 'email3'){
			document.getElementById('pledge').focus();
			return false;
			}
		if(f.getAttribute('id') == 'pledge'){
			document.getElementById('booking').focus();
			return false;
			}
	   }
	   return true;
	}


function loadRoomOnPopup(roomtypeId,date,span,callback)
{
	var link = "/popupService?doClass=loadRoomG&roomtype=" + roomtypeId + "&date=" + date+"&span="+span+"&roomid="+roomId;
	simpleservice(link,null,callback);
}

function popupDialog(el,callback)
{
	$(el).dialog({
		resizable : false,
		modal : true,
		show : {
			effect : "blind",
			duration : 500
		},
		buttons : {
			Ok : function() {
				callback();
				$(this).dialog("close");
			}
		}
	});
}
function EditDialogHeader(roomName,roomType)
{
	$("#BookingG").parent().find(".ui-dialog-titlebar").hide();
	var htmlText = '<div id = "edit_new_dialog_header" >'+
		'<table width=\"100%\">'+
		'<tr valign="center">'+
		'<td width=\"93px\"><span>'+reserved_room+'&nbsp;&nbsp;</span></td>'+
		'<td width=\"513px\">'+
		'<span name =\"rmt\" id=\"rmt\" roomtype="'+roomType+'">'+getRoomTypeId(roomType).shortName + '</span>'+
			'<span>'+
		'&nbsp;&nbsp;<select name="roomOnPopup" >'+
			'<option>'+select_room +'</option>'+
			'</select></span>'+
			'</td>'+
			'<td width=\"91px\">'+
		'<span >'+
			'<input  type=\"checkbox\" name=\"isAssign\" value=\"isAssign\">'+assign_room +'</span>'+
			'</td>'+
			'<td width=\"36px\">'+
			'<span id=\"closereservedG\" class=\"colse_icon \" onclick="closeDialog(id)"></span>'+
			'</td>'+
			'</tr>'+
			'</table>'+
			'</div>';
	
	if($("[id*=edit_new_dialog_header]").size() == 0)
		$($("#BookingG").parent().children()[0]).before(htmlText);	
}

function AddToNewGroup(){
	var resIdArray = "";
	for(var j = 0;j<$('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]').length;j++){
		if($('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j].checked == true){
			resIdArray += $('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j].id+",";
		}
	}
	if(resIdArray==""){
		simpleDialog(pleaseSelectReservationAddToNewGroup);
	}else{
		var size = { width: 600, height: 70};
		/// Solution
		var opts = SharedData.Salutation.length;
		if($("#AddToGroupSolutation > option").length == 0)
			for ( var i = 0; i < opts; i++)
				$("#AddToGroupSolutation").append( $("<option>").val(SharedData.Salutation[i].id).html(SharedData.Salutation[i].title));
		var buttons = [
		   { title:"OK" , callback: function(thisdialog,args){
			    var salutation = thisdialog.find("#AddToGroupSolutation").val();
				var name = thisdialog.find("#addToGroupFName").val();
				var lastname = thisdialog.find("#addToGroupLName").val();
				var phone = thisdialog.find("#addToGroupPhone").val();
				var company = thisdialog.find("#addToGroupCompany").val();
			    if(name == ""){
					thisdialog.find("#addToGroupFName").select();
					//simpleDialog(emptyName);
				}else if(lastname==""){
					thisdialog.find("#addToGroupLName").select();
				}else{
					waitingDialog({});
					confirmDialog(confirmAddReservationANewgroup,function() {
					var resIdArray = "";
					var pracketPriceId = "";
					var roomTypeId = "";
					var checkaddPracket = 0;
					for(var j = 0;j<$('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]').length;j++){
						if($('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j].checked == true){
							resIdArray += $('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j].id+",";
							if(checkaddPracket==0){
								pracketPriceId = $($('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j]).attr("pracketpriceid");
								roomTypeId = $($('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j]).attr("pracketpriceid");
							}
						}
					}
					
					var resId=resIdArray.substr(0, resIdArray.length-1);
						var setDateFormat = new Date();
						var setYear = setDateFormat.getFullYear();
						var setMonth = setDateFormat.getMonth()+1;
						var setDay = setDateFormat.getDate();
						var date = setYear+'-'+setMonth+'-'+setDay;
					var link = "/reservationService?func=createGroupRoomManage&hotelId=" + hotelId
					+ "&date=" + date + "&span=" + '1' + "&rmType=" + roomTypeId + "&priceRate=" + pracketPriceId + 
					"&pay="+ '0'+"&salutation="+salutation+"&nameguestGroup="+name+"&lastnameguestGroup="+lastname+
					"&tellgusetGroup="+phone+"&agencygusetGroup="+''+"&note="+''+"&reason="+ ''+
					"&source=" +''+"&extrabed="+'0'+
					"&resId="+resId+"&agency="+company+"&company="+company;
							simpleserviceSyn(link,null,createToNewGroupSuccess,thisdialog);
					});
					//$(".ui-dialog").last().css("z-index",200005);
				}
		   }},
		   { title:"Cancel" , callback: function(thisdialog,args){
			   thisdialog.dialog("close");
		   }}
		];
		customDialog(popupTitle,$("#AddToNewGroup").html(),size,buttons,null);
	}
}

function createToNewGroupSuccess(data,thisdialog){
	var objArray = JSON.parse(data);
	var checkLogOut = CheckSession(objArray);
	if(checkLogOut)
		return;
	var indexPush = 0;
	var countIndex = 0;
	var arrayListResv = objArray[0].resList.split(",");
	for(var i =0;i<arrayListResv.length;i++){
		for(var j = 0;j<oldObjArrayAllReservation[0].length;j++){
			if(oldObjArrayAllReservation[0][j]!=undefined){
				if(arrayListResv[i]==oldObjArrayAllReservation[0][j].id){
					if(countIndex==0){
						indexPush = j;
						countIndex++;
					}
					delete oldObjArrayAllReservation[0][j];
				}
			}
		}
	}
	oldObjArrayAllReservation[0] = oldObjArrayAllReservation[0].filter(function(a){return typeof a !== 'undefined';});
	oldObjArrayAllReservation[0].splice(indexPush,0,objArray[0]);
	indexPush = 0;
	showDataResRoomAllManageMent(JSON.stringify(oldObjArrayAllReservation));
	/*DisplayframeMainMenu("Front Desk");*/
	cerltimespan(savedSpan);
	thisdialog.dialog("close");
	closeWaitingDialog();
}
function confirmRemoveFromGroupFunction(){
	var subresIdArray = "";
	for(var j = 0;j<$('#allReservation tr [type=checkbox][name=subReservation]').length;j++){
		if($('#allReservation tr [type=checkbox][name=subReservation]')[j].checked == true){
			subresIdArray += $($('#allReservation tr [type=checkbox][name=subReservation]')[j]).attr("subres")+",";
		}
	}
	if(subresIdArray==""){
		simpleDialog(pleaseSelectReservationRemoveFromGroup);
	}else{
		var checkGuest;
		var checkAgency; 
		var countGuest = 0;
		var countAgency = 0;
		for(var j = 0;j<$('#allReservation tr [type=checkbox][name=subReservation]').length;j++){
			if($('#allReservation tr [type=checkbox][name=subReservation]')[j].checked == true){
				var resId = $($('#allReservation tr [type=checkbox][name=subReservation]')[j]).attr("subres");
				checkGuest = $('#allReservation tr [id="'+resId+'"]').html();
				if(checkGuest=="-"){
					countGuest++;
				}
			}
		}
		
		for(var j = 0;j<$('#allReservation tr [type=checkbox][name=subReservation]').length;j++){
			if($('#allReservation tr [type=checkbox][name=subReservation]')[j].checked == true){
				var resId = $($('#allReservation tr [type=checkbox][name=subReservation]')[j]).attr("subres");
				checkAgency = $('#allReservation tr [id="'+resId+'"]').attr("agency");
				if(checkAgency!="undefined"&&checkAgency!=""&&checkAgency!=undefined){
					countAgency++;
				}
			}
		}
		if(countGuest>0){
			simpleDialog(guestEmpty);
		}else if(countAgency>0){
			simpleDialog(agencyEmpty);
		}else{
			waitingDialog({});
			confirmDialog(confirmRemoveFromGroup,RemoveFromGroup);
		}
	}
}

function RemoveFromGroup(){
	var subresIdArray = [];
	var countGroup = 0;
	var checkGroup = 0;
	var oldGroup = "";
	var multiResId = "";
	var countCheckedBox = 0;
	var groupId = "";
	for(var j = 0;j<$('#allReservation tr [type=checkbox][name=subReservation]').length;j++){
		if($('#allReservation tr [type=checkbox][name=subReservation]')[j].checked == true){
			groupId = $($('#allReservation tr [type=checkbox][name=subReservation]')[j]).attr("groupid");
			if(checkGroup==groupId||countGroup==0){
				multiResId += $($('#allReservation tr [type=checkbox][name=subReservation]')[j]).attr("subres")+",";
				checkGroup = groupId;
				oldGroup = groupId;
				countGroup++;
				if(j==$('#allReservation tr [type=checkbox][name=subReservation]').length-1){
					var multiResIdInput=multiResId.substr(0, multiResId.length-1);
					subresIdArray.push({groupId:oldGroup,subRes:multiResIdInput});
					multiResId="";
				}
			}else{
				var multiResIdInput=multiResId.substr(0, multiResId.length-1);
				subresIdArray.push({groupId:oldGroup,subRes:multiResIdInput});
				multiResId="";
				multiResId += $($('#allReservation tr [type=checkbox][name=subReservation]')[j]).attr("subres")+",";
				checkGroup = groupId;
			}
		}		
	}
	if(multiResId!=""){
		var multiResIdInput=multiResId.substr(0, multiResId.length-1);
		subresIdArray.push({groupId:groupId,subRes:multiResIdInput});
	}
	var dataforJava = "";
	for(var i =0;i<subresIdArray.length;i++){
		dataforJava +=  JSON.stringify(subresIdArray[i])+"_";
	}
	var objArrayJsonforJava=dataforJava.substr(0, dataforJava.length-1);
	var link = "/reservationService?func=removeFromGroupRoomManage&hotelId=" + hotelId
	+ "&dataArray="+objArrayJsonforJava;
	simpleserviceSyn(link,null,deleteResInGroupSuccess);
}

function deleteResInGroupSuccess(data){
	var objArray = JSON.parse(data);
	var checkLogOut = CheckSession(objArray);
	if(checkLogOut)
		return;
	var groupDelete = [];
	for(var i = 0;i<objArray.length;i++){ /// Loop New Object
		for(var j = 0;j<oldObjArrayAllReservation[0].length;j++){ /// Loop Old Object
			if((objArray[i][0].groupId==oldObjArrayAllReservation[0][j].groupId)&&oldObjArrayAllReservation[0][j].groupId!=0){ // check same GroupId
				if(objArray[i][0].resList!=undefined){ // check res in Group
					var resNowGroup = objArray[i][0].resList.split(",");
					if(oldObjArrayAllReservation[0][j].resList==undefined){continue;}
					var resOldGroup = oldObjArrayAllReservation[0][j].resList.split(",");
					var resConCat = resNowGroup.concat(resOldGroup)
						.filter(function (item, index, array) {
							return array.indexOf(item) == array.lastIndexOf(item);
						}); // ConCat get Single Reservation
					for(var rc = 0; rc<resConCat.length;rc++){ // Loop Delete Single In Old Object
						var resOldGroup = oldObjArrayAllReservation[0][j].resList.split(",");
						for(var o =0; o<resOldGroup.length;o++){
							if(resConCat[rc]==resOldGroup[o]){
								for(var d=0;d<oldObjArrayAllReservation[0][j].subList.length;d++){
									if(resConCat[rc]==oldObjArrayAllReservation[0][j].subList[d].id){
										oldObjArrayAllReservation[0][j].subList[d].groupId = "0";
										oldObjArrayAllReservation[0].push(oldObjArrayAllReservation[0][j].subList[d]);
									}
								}
							}
						}
					}
				}
				delete oldObjArrayAllReservation[0][j];
				
				oldObjArrayAllReservation[0] = oldObjArrayAllReservation[0].filter(function(a){return typeof a !== 'undefined';});
				oldObjArrayAllReservation[0].splice(j,0,objArray[i][0]);
				oldObjArrayAllReservation[0] = UniqueStringResIds(oldObjArrayAllReservation[0]);
				sortIdRoommanagement(oldObjArrayAllReservation[0]);
			}else if(objArray[i][0].groupId==0){
				var resRemoveIngroup;
					for(var od=0;od<objArray.length;od++){ // remove
						for(var d=0;d<oldObjArrayAllReservation[0].length;d++){ // old data
							if(oldObjArrayAllReservation[0][d].subList!=undefined){ // check resList or check group
								for(var dr = 0;dr<oldObjArrayAllReservation[0][d].subList.length;dr++){ // res_in_group for delete
									for(var resRemove=0;resRemove<objArray[od].length;resRemove++){ //loop remove check in res_in_group
										resRemoveIngroup = objArray[od][resRemove].id; 
										if(oldObjArrayAllReservation[0][d].subList[dr].id==resRemoveIngroup){
											groupDelete.push(oldObjArrayAllReservation[0][d].groupId);
											oldObjArrayAllReservation[0].push(objArray[od][resRemove]);
										}
									}
								}
							}
						}
					}
			//	oldObjArrayAllReservation = UniqueArray(oldObjArrayAllReservation);
				
				groupDelete = UniqueString(groupDelete);
				
				for(var gc = 0;gc<groupDelete.length;gc++){
					for(var d=0;d<oldObjArrayAllReservation[0].length;d++){
						if(groupDelete[gc]==oldObjArrayAllReservation[0][d].groupId){
							delete oldObjArrayAllReservation[0][d];
							oldObjArrayAllReservation[0] = oldObjArrayAllReservation[0].filter(function(a){return typeof a !== 'undefined';});
						}
					}
				}
				oldObjArrayAllReservation[0] = oldObjArrayAllReservation[0].filter(function(a){return typeof a !== 'undefined';});
				
				sortIdRoommanagement(oldObjArrayAllReservation[0]);
			}
		}
	}
	sortIdRoommanagement(oldObjArrayAllReservation[0]);
	pager.showPage(getCurrentTabData().pagerNumber);
	componentLoading($('#tappage_newpage_CheckInListRoomManageMent'));
	getReservationRoomAllManageMent('CheckInListRoomManageMent',getCurrentTabData().pagerNumber);
	//showDataResRoomAllManageMent(JSON.stringify(oldObjArrayAllReservation));
	/*DisplayframeMainMenu("Front Desk");*/
	cerltimespan(savedSpan);
	closeWaitingDialog();
}
function confirmAddFromGroupFuction(){
	var resIdArray = "";
	var groupSet = "";
	var checkAgency = "";
	for(var j = 0;j<$('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]').length;j++){
		if($('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j].checked == true){
			resIdArray += $('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j].id+",";
		}
	}
	for(var j = 0;j<$('#allReservation tr [type=radio][group]').length;j++){
		if($('#allReservation tr [type=radio][group]')[j].checked == true){
			groupSet = $($('#allReservation tr [type=radio][group]')[j]).attr("group");
		}
	}
	if(resIdArray==""){
		simpleDialog(pleaseSelectReservationAddToGroup);
	}else if(groupSet==""){
		simpleDialog(pleaseSelectGroup);
	}else{
		
		for(var j = 0;j<$('#allReservation tr [type=radio][group]').length;j++){
			if($('#allReservation tr [type=radio][group]')[j].checked == true){
				checkAgency = $($('#allReservation tr [type=radio][group]')[j]).attr("agency");
			}
		}
		if(checkAgency!=undefined&&checkAgency!=""&&checkAgency!="undefined"){
			simpleDialog(agencyEmpty);
		}else{
			waitingDialog({});
			confirmDialog(confirmAddReservationToGroup,function() {
				AddFromGroup(groupSet);
			});
		}
	}
}
function AddFromGroup(groupSet){
	var subresIdArray = [];
	var countGroup = 0;
	var checkGroup = 0;
	var oldGroup = "";
	var multiResId = "";
	var countCheckedBox = 0;
	for(var j = 0;j<$('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]').length;j++){
		if($('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j].checked == true){
			multiResId += $('#allReservation tr [type=checkbox][name=checkboxAddToNewGroup]')[j].id+",";
			checkGroup = groupSet;
			oldGroup = groupSet;
		}		
	}
	if(multiResId!=""){
		var multiResIdInput=multiResId.substr(0, multiResId.length-1);
		subresIdArray.push({groupId:groupSet,subRes:multiResIdInput});
	}
	var dataforJava = "";
	for(var i =0;i<subresIdArray.length;i++){
		dataforJava +=  JSON.stringify(subresIdArray[i])+"_";
	}
	var objArrayJsonforJava=dataforJava.substr(0, dataforJava.length-1);
	var link = "/reservationService?func=addFromGroupRoomManage&hotelId=" + hotelId
	+ "&dataArray="+objArrayJsonforJava;
	simpleserviceSyn(link,null,addToGroupSuccess,multiResIdInput);
}
function addToGroupSuccess(data,multiResIdInput){
	var objArray = JSON.parse(data);
	var checkLogOut = CheckSession(objArray);
	if(checkLogOut)
		return;
	var groupDelete = [];
	var resRemoveOldObjArrayAllReservation = multiResIdInput.split(",");
	var indexArray = 0;
	for(var i =0;i<resRemoveOldObjArrayAllReservation.length;i++){
		 var resRemove = resRemoveOldObjArrayAllReservation[i]
		 for(var j = 0;j<oldObjArrayAllReservation[0].length;j++){
			 if(resRemove==oldObjArrayAllReservation[0][j].id){
				 delete oldObjArrayAllReservation[0][j];
				 oldObjArrayAllReservation[0] = oldObjArrayAllReservation[0].filter(function(a){return typeof a !== 'undefined';});
			 }
		 }
	}
	sortIdRoommanagement(oldObjArrayAllReservation[0]);
	if(oldObjArrayAllReservation[0][oldObjArrayAllReservation[0].length-1].subList!=undefined){
		if($("#Rowpager"+getCurrentTabData().pageName+" option:selected").attr("value")!="All"){
			var optionId = $("#Rowpager"+getCurrentTabData().pageName+" option:selected").attr("id");
			var number =  parseInt(optionId.substr(optionId.length-1))+1;
			var subStrOptionId = optionId.substr(0,optionId.length-1)+number;
			for(var i =0;i<$("#Rowpager"+getCurrentTabData().pageName+" option").length;i++){
				if($($("#Rowpager"+getCurrentTabData().pageName+" option")[i]).attr("id")==subStrOptionId){
					//$($("#Rowpager"+getCurrentTabData().pageName+" option")[i]).attr('selected', 'selected');
					//getCurrentTabData().lineAllreservation = $($("#Rowpager"+getCurrentTabData().pageName+" option")[i]).attr('selected', 'selected').text();
					pager.showPage(getCurrentTabData().pagerNumber);
					componentLoading($('#tappage_newpage_CheckInListRoomManageMent'));
					getReservationRoomAllManageMent('CheckInListRoomManageMent',getCurrentTabData().pagerNumber);
				}
			}
		}else{
			deleteResInGroupSuccess(data);
		}
		
	}
	closeWaitingDialog();
}
